<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        ul,
        li,
        ol,
        dl,
        dt,
        dd,
        div,
        p,
        span,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6,
        a {
            padding: 0px;
            margin: 0px;
        }

        div {
            width: 200px;
            height: 200px;
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            background-color: #ff6700;
            cursor: move;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        window.addEventListener('load', function () {
            var div = document.querySelector('div');
            //1.获取鼠标在盒子内的坐标
            div.addEventListener('mousedown', function (e) {
                console.log(e);
                var x = e.pageX - this.offsetLeft;
                var y = e.pageY - this.offsetTop;
                this.innerHTML = 'X坐标:' + x + ' Y坐标:' + y;

                // (2) 鼠标移动的时候，把鼠标在页面中的坐标，减去 鼠标在盒子内的坐标就是模态框的left和top值
                document.addEventListener('mousemove', move);

                function move(e) {
                    console.log(e);
                    div.style.left = e.pageX - x  + 'px';
                    div.style.top = e.pageY - y  + 'px';
                }
                // (3) 鼠标弹起，就让鼠标移动事件移除
                document.addEventListener('mouseup', function () {
                    document.removeEventListener('mousemove', move);
                })
            })

        })
    </script>
</body>

</html>